package com.buka.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buka.api.OrderApi;
import com.buka.common.BizCodeEnum;
import com.buka.config.MQConfig;
import com.buka.constants.Constants;
import com.buka.dao.CouponTaskDao;
import com.buka.entity.CouponRecord;
import com.buka.entity.CouponTask;
import com.buka.interceptor.LoginUserInterceptor;
import com.buka.message.CouponMessage;
import com.buka.request.LockCouponRequest;
import com.buka.service.CouponRecordService;
import com.buka.service.CouponTaskService;
import com.buka.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * (CouponTask)表服务实现类
 *
 * @author makejava
 * @since 2025-08-18 14:17:24
 */
@Service("couponTaskService")
@Slf4j
public class CouponTaskServiceImpl extends ServiceImpl<CouponTaskDao, CouponTask> implements CouponTaskService {

    @Resource
    private CouponRecordService couponRecordService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    MQConfig mqConfig;

    @Resource
    private OrderApi orderApi;

    @Override
    @Transactional
    public JsonData lockCoupon(LockCouponRequest lockCouponRequest) {
        //锁定优惠券具体逻辑

        //校验优惠券，查询条件  用户的id + couponId
        List<Long> couponRecordIdList = lockCouponRequest.getCouponRecordIdList();
        for (Long couponRecordId : couponRecordIdList) {
            //同一个优惠券，可以重复领取
            LambdaQueryWrapper<CouponRecord> couponRecordWrapper = Wrappers.lambdaQuery(CouponRecord.class);
            couponRecordWrapper.eq(CouponRecord::getId,couponRecordId)
                            .eq(CouponRecord::getUserId,lockCouponRequest.getUserId())
                                    .eq(CouponRecord::getUseState, Constants.CoupUseStateEnum.NEW.name());
            CouponRecord couponRecord = couponRecordService.getOne(couponRecordWrapper);
            if(ObjectUtil.isEmpty(couponRecord)){
                //如果没有查询到可以用优惠券，返回异常提示
                return JsonData.buildResult(BizCodeEnum.COUPON_NO_USE);
            }

            //修改优惠券为已使用状态
            couponRecord.setUseState(Constants.CoupUseStateEnum.USED.name());
            couponRecordService.updateById(couponRecord);

            //添加库存锁定表记录
            CouponTask couponTask = new CouponTask();
            couponTask.setCouponRecordId(couponRecord.getId());
            couponTask.setOutTradeNo(lockCouponRequest.getOutTradeNo());
            couponTask.setLockState(Constants.StockTaskStateEnum.LOCK.name());
            //存入数据库
            save(couponTask);

            //发送发送延时消息，构造一个优惠券消息
            CouponMessage couponMessage = new CouponMessage();
            couponMessage.setTaskId(couponTask.getId());
            couponMessage.setOutTradeNo(lockCouponRequest.getOutTradeNo());

            rabbitTemplate.convertAndSend(mqConfig.getCouponExchange(),
                    mqConfig.getCouponReleaseDelayRoutingKey(),couponMessage);


        }

        return JsonData.buildSuccess();
    }

    @Override
    public boolean updateState(CouponMessage couponMessage) {

        try {
            //获取锁定任务记录，先校验一次任务状态是否为锁定，如果已经解锁了，下面的逻辑就不需要操作
            CouponTask couponTask = getById(couponMessage.getTaskId());
            if(null == couponTask){ //为空的时候放行，说明已经完成了或删除了
                return true;
            }

            String lockState = couponTask.getLockState();
            //不是锁定状态是  ，放行
            if(!Constants.StockTaskStateEnum.LOCK.name().equals(lockState)){
                return true;
            }
            //是锁定状态，获取订单编号，查询订单状态
            String outTradeNo = couponMessage.getOutTradeNo();
//            JsonData jsonData = JsonData.buildSuccess();
            JsonData jsonData = orderApi.queryOrderState(outTradeNo);
            if(jsonData.getCode() != 0){
                //订单状态查询失败，消息拒绝消费，重新放回队列
                return false;
            }

            String orderState = (String) jsonData.getData();
            //校验订单状态
            if(Constants.OrderStatusEnum.PAY.name().equals(orderState)){//已支付状态
                //修改锁定任务表状态为完成
                couponTask.setLockState(Constants.StockTaskStateEnum.FINISH.name());
                updateById(couponTask);
                return true;
            }else if(Constants.OrderStatusEnum.CANCEL.name().equals(orderState)){
                //取消状态  修改锁定任务表状态为取消,并修改和优惠券的状态为可用
                couponTask.setLockState(Constants.StockTaskStateEnum.CANCEL.name());
                updateById(couponTask);
                //优惠券记录的id
                Long couponRecordId = couponTask.getCouponRecordId();
                LambdaUpdateWrapper<CouponRecord> couponRecordWrapper = Wrappers.lambdaUpdate(CouponRecord.class);
                couponRecordWrapper.set(CouponRecord::getUseState,Constants.CoupUseStateEnum.NEW.name())
                        .eq(CouponRecord::getId,couponRecordId);
                couponRecordService.update(couponRecordWrapper);
                return true;
            }
        }catch (Exception e){
            log.error("优惠券任务处理失败：{}",e.getMessage());
        }
        return false;
    }
}

